#version 120

varying vec3 normal, lightDir;

uniform int useTexture;
uniform sampler2D tLowest;
uniform sampler2D tMedium;
uniform sampler2D tHigh;
uniform sampler2D tHighest;
uniform vec3 diffuseColor;

varying vec3 position;

uniform sampler2D noise;

void main()
{
	vec3 color;
	if(useTexture == 1) {
		vec3 color1 = texture2D(tLowest, gl_TexCoord[0].st).rgb;
		vec3 color2 = texture2D(tMedium, gl_TexCoord[0].st).rgb;
		vec3 color3 = texture2D(tHigh, gl_TexCoord[0].st).rgb;
		vec3 color4 = texture2D(tHighest, gl_TexCoord[0].st).rgb;
		float a = -0.05; // lowest
		float d = 0.1; // highest
		float b = a+(d-a)*1./3.; // medium
		float c = a+(d-a)*2./3.;  // high
		// a < b < c < d
		float p; // interpolation value in [0,1]
		if(position.y < b) {
			p = (position.y-a)/(b-a);
			color = color1*(1-p)+color2*p;
		} else if(b <= position.y && position.y < c) {
			p = (position.y-b)/(c-b);
			color = color2*(1-p)+color3*p;
		} else {
			p = (position.y-c)/(d-c);
			color = color3*(1-p)+color4*p;
		}
		
		//color = texture2D(tLowest, gl_TexCoord[0].st).rgb; // only for sand
	} else {
		color = vec3(position.y);
		color = vec3(0.5, 0.5, 0.5);
	}
	
	vec4 final_color = vec4(0.0);
	vec3 N = normalize(normal);
	vec3 L = normalize(lightDir);
	float lambertTerm = dot(N, L);
	float ambientTerm = 0.3;
	if(lambertTerm > 0.0)
	{
		final_color += vec4(color, 1.0) * (ambientTerm + lambertTerm);	
	}

	gl_FragColor = final_color;
}